package com.javaEE.gamepigeon.service.impl;

import com.javaEE.gamepigeon.dao.LoginDao;
import com.javaEE.gamepigeon.entity.User;
import com.javaEE.gamepigeon.service.LoginService;
import com.javaEE.gamepigeon.util.HttpRequest;
import com.javaEE.gamepigeon.util.JwtTokenUtil;
import com.javaEE.gamepigeon.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

@Component
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginDao loginDao;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private HttpRequest httpRequest;

    /**
     * 根据用户返回的code从微信服务器获取openId
     * @param code 用户code
     * @return 返回是否登录成功及token
     */
    public Result login(String code){
        ResponseEntity<String> responseEntity = httpRequest.sendWxToLogin(code);
        String string = responseEntity.getBody();
        System.out.println(responseEntity);
       if(responseEntity.getStatusCode().equals(HttpStatus.OK)) {
           String[] strs = string.split("\"");
           try{
               String openid = strs[7];
               User user = loginDao.queryUserByOpenId(openid);
               if(null != user){
                   String token = jwtTokenUtil.generateTokenByOpenId(user);
                   token = "Bearer "+token;
                   return Result.success("用户登录成功！",token);
               }else{
                   Integer integer = loginDao.insertUserByOpenId(openid);
                   if(integer ==1){
                       user = new User();
                       user.setOpenId(openid);
                       String token = jwtTokenUtil.generateTokenByOpenId(user);
                       token = "Bearer "+token;
                       return Result.success("新用户新增成功！",token);
                   }else{
                       return Result.error("新用户录入时后端出现问题！");
                   }
               }
           }catch (Exception exception){
               return Result.error("不能重复用code！",exception.toString());
           }
       }
        return Result.error("用户登录失败！");
    }

}
